package com.wframe.project.former.web.couponSet;


import com.frame.database.JdataBean;
import com.frame.database.PageResult;
import com.frame.pageform.DataPageForm;
import com.frame.pageform.RequestContext;
import com.frame.util.DataConvert;
import com.frame.util.DateConvert;
import com.wframe.project.former.dataservices.coupon.CouponService;
import com.wframe.project.former.dataservices.marketing.PromotionsService;
import com.wframe.project.former.dataservices.marketing.SingService;
import com.wframe.project.former.dataservices.products.ProductClassService;
import com.wframe.project.former.dataservices.products.ProductService;
import com.wframe.project.former.dataservices.user.UserService;
import com.wframe.project.jnd.util.FileUtils;
import com.wframe.project.jnd.util.TransformUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

public class CouponSetPage extends DataPageForm {
    private JdataBean bean;
    private CouponService couponService = CouponService.getIntance();
    private PromotionsService promotionsService = PromotionsService.getIntance();
    private UserService userService = UserService.getIntance();
    private static SingService singService = SingService.getIntance();

    @Override
    public String execute() throws Exception {
        setPagination(couponService.queryCoupon(bean, getPageSize_(), getPageNum()));
        return "/webadmin/couponSet/couponList.jsp";
    }

    public String details() throws Exception {
        setPagination(couponService.queryCouponDetails(bean, getPageSize_(), getPageNum()));
        return "/webadmin/couponSet/couponDetails.jsp";
    }

    @Override
    public String show() throws Exception {
        if (bean != null && StringUtils.isNotBlank(bean.getString("id"))) {
            bean = couponService.getCoupon(bean.getString("id"));
            if (bean.getInt("product_type") == 1) {
                JdataBean selectedPro = singService.querySelectedProduct(bean.getInt("product_val"));
                if (selectedPro != null) {
                    selectedPro.put("types", promotionsService.getProductMoneyOffTypeById(bean.getString("product_val")));
                    ProductClassService pcservice = ProductClassService.getIntance();
                    ProductService service = ProductService.getIntance();
                    selectedPro.put("price", promotionsService.getProducrPrice(String.valueOf(selectedPro.get("id"))));
                    List<JdataBean> jdataBeans = service.queryAllModelAttrAndVal("1", String.valueOf(selectedPro.get("id")), 1);
                    for (JdataBean attr : jdataBeans) {
                        selectedPro.put(attr.getString("code"), attr.get("val"));
                    }
                    selectedPro.put("classname", pcservice.getProductClassName(String.valueOf(selectedPro.getString("id"))));
                    getRequest().setAttribute("selectedPro", selectedPro);
                }
            }
        } else {
            bean = new JdataBean();
            bean.put("state", 1);
        }
        return "/webadmin/couponSet/couponEdit.jsp";
    }

    public String addcoupon() throws Exception {
        return "/webadmin/couponSet/addCoupon.jsp";
    }

    public String SendCoupon() throws Exception {
        return "/webadmin/couponSet/sendCoupon.jsp";
    }

    @Override
    public String toDel() throws Exception {
        Map key = new HashMap();
        key.put("id", bean.getString("id"));
        JdataBean data = new JdataBean();
        data.put("state", 2);
        couponService.update(data.getDataMap(), key);
        return getJsonObject().toString();
    }

    @Override
    public boolean toUpdate() {
        try {
            JdataBean coupon = new JdataBean();
            String platform = bean.getString("platform");
            coupon.put("source", platform);
            coupon.put("name", bean.getString("couponname"));
            Date date = new Date();
            if (bean.getInt("fixed") == 0) {
                //固定有效期
                coupon.put("activity_day", null);
                coupon.put("startdate", bean.getString("fixedstarttime"));
                coupon.put("enddate", bean.getString("fixedendtime"));
            } else {
                //活动有效期
                coupon.put("activity_day", bean.getString("activelife"));
                coupon.put("startdate", date);
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(date);
                calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) + bean.getInt("activeLife"));
                coupon.put("enddate", calendar.getTime());
            }
            coupon.put("explanation", bean.getString("couponDescribe"));
            coupon.put("offer_money", bean.getString("couponDenomination"));
            coupon.put("min_money", bean.getString("min_money"));
            coupon.put("amount", TransformUtils.getValue(bean.getString("amount")));

            int exchange = bean.getInt("convertible");
            coupon.put("exchange", exchange);
            if (exchange == 1) {
                coupon.put("exchange_starttime", bean.getString("exchange_starttime"));
                coupon.put("exchange_endtime", bean.getString("exchange_endtime"));
            } else {
                coupon.put("exchange_starttime", null);
                coupon.put("exchange_endtime", null);
            }

            int receive = bean.getInt("receive");
            coupon.put("receive", receive);
            if (receive == 1) {
                coupon.put("receive_starttime", bean.getString("receive_starttime"));
                coupon.put("receive_endtime", bean.getString("receive_endtime"));
                coupon.put("limit_num", bean.getString("limit_num"));
            } else {
                coupon.put("receive_starttime", null);
                coupon.put("receive_endtime", null);
                coupon.put("limit_num", 0);
            }

            JdataBean promotion = new JdataBean();
            promotion.put("platform", platform);
            if (receive == 1) {
                promotion.put("start_time", bean.getString("receive_starttime"));
                promotion.put("end_time", bean.getString("receive_endtime"));
            } else {
                promotion.put("start_time", null);
                promotion.put("end_time", null);
            }
            String promotionid = bean.getString("promotionid");
            //添加
            if (StringUtils.isBlank(promotionid)) {
                promotion.put("promotion_type", 4);
                promotionid = promotionsService.addPromotions(promotion);
            }

            Map key = new HashMap();
            key.put("id", promotionid);

            int productType = bean.getInt("product_type");
            promotion.put("product_type", productType);
            if (productType == 2) {
                promotion.put("product_type", 1);
                promotion.put("product_val", bean.getString("product_val"));
            } else if (productType == 3) {
                promotion.put("product_val", bean.getString("classid"));
            }
            promotionsService.update(promotion.getDataMap(), key);

            String id = bean.getString("id");
            if (StringUtils.isBlank(id)) {
                coupon.put("type", 1);
                coupon.put("tag", 0);
                coupon.put("state", 1);
                coupon.put("create_time", date);
                coupon.put("promotionid", promotionid);
                couponService.saveCoupon(coupon.getDataMap());
            } else {
                Map keymap = new HashMap<>();
                keymap.put("id", id);
                couponService.update(coupon.getDataMap(), keymap);
            }

            getJsonObject().put("state", "ok");
        } catch (Exception e) {
            Logger.getLogger(this.getClass()).error("保存商品信息错误：", e);
            getJsonObject().put("state", e.getMessage());
        }
        return false;
    }

    public String userselQuery() throws Exception {
        getRequest().setAttribute("province", userService.getProvince());
        setPagination(userService.queryUserInfo(bean, getPageSize_(), getPageNum()));
        return "/webadmin/couponSet/sendCoupon.jsp";
    }

    public String cityQuery() throws Exception {
        getJsonObject().put("city", userService.getCity(bean.getString("pid")));
        return getJsonObject().toString();
    }

    /**
     * 发送优惠劵
     *
     * @return
     * @throws Exception
     */
    public String send() throws Exception {
        couponService.send(bean.getString("id"), bean.getString("userids").split(","));
        getJsonObject().put("state", "ok");
        return getJsonObject().toString();
    }

    public void exportXls() throws Exception {
        List<JdataBean> list = couponService.queryCouponDetails(bean);
        int size = list.size();
        HSSFWorkbook workbook = new HSSFWorkbook();
        for (int i = 1; i <= (size + 65534) / 65535; i++) {
            // 创建一个sheet页
            HSSFSheet sheet = workbook.createSheet("优惠券" + i);
            // 创建标题行
            HSSFRow headRow = sheet.createRow(0);
            headRow.createCell(0).setCellValue("来源");
            headRow.createCell(1).setCellValue("用户名");
            headRow.createCell(2).setCellValue("手机号码");
            headRow.createCell(3).setCellValue("企业名称");
            headRow.createCell(4).setCellValue("领取时间");
            headRow.createCell(5).setCellValue("使用时间");
            headRow.createCell(6).setCellValue("使用状态");

            for (int j = (i - 1) * 65536; j < i * 65536 - 1 && j < size; j++) {
                JdataBean data = list.get(j);
                HSSFRow dataRow = sheet.createRow(sheet.getLastRowNum() + 1);
                String source = DataConvert.toString(data.getString("get_source"), "[发送,发送,发送,领取,兑换]");
                if (StringUtils.isBlank(source)) {
                    source = "发送";
                }
                dataRow.createCell(0).setCellValue(source);
                dataRow.createCell(1).setCellValue(data.getString("title"));
                dataRow.createCell(2).setCellValue(data.getString("phone"));
                dataRow.createCell(3).setCellValue(data.getString("name"));
                Object createTime = data.get("create_time");
                if (createTime != null) {
                    dataRow.createCell(4).setCellValue(DateConvert.toDefaultString((Date) createTime));
                } else {
                    dataRow.createCell(4).setCellValue("");
                }

                Object useTime = data.get("use_time");
                if (useTime != null) {
                    dataRow.createCell(5).setCellValue(DateConvert.toDefaultString((Date) useTime));
                } else {
                    dataRow.createCell(5).setCellValue("");
                }

                dataRow.createCell(6).setCellValue(DataConvert.toString(data.getString("tag"), "[未使用,已使用]"));
            }
        }

        String filename = "优惠券详情.xls";
        String agent = getRequest().getHeader("User-Agent");
        filename = FileUtils.encodeDownloadFilename(filename, agent);
        HttpServletResponse response = getResponse();
        ServletOutputStream out = response.getOutputStream();
        String contentType = RequestContext.getContext().getServlet().getServletContext().getMimeType(filename);
        response.setContentType(contentType);
        response.setHeader("content-disposition", "attchment;filename=" + filename);
        workbook.write(out);
    }

    public JdataBean getBean() {
        return bean;
    }

    public void setBean(JdataBean bean) {
        this.bean = bean;
    }
}
